package com.efa.backend.base.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.efa.backend.base.entity.HisProductProfit;
import com.efa.backend.base.entity.ProductDetail;
import com.efa.backend.base.repository.HisProductProfitRepository;
import com.efa.backend.base.repository.ProductDetailRepository;
import com.efa.backend.base.service.ProductDetailService;
import com.efa.backend.framework.utility.DateUtil;

/**
 * @Description: TODO
 * @author zhaoxin
 * @date 2014年3月12日 下午8:05:00
 * @version V1.0
 */

@Service(value = "productDetailService")
public class ProductDetailServiceImpl implements ProductDetailService {
	@Autowired
	private ProductDetailRepository productDetailRepository;

	@Autowired
	private HisProductProfitRepository hisProductProfitRepository;

	/**
	 * 查询产品基本信息和对应的历史收益表
	 * 
	 * @param queryDay
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@Override
	public List<ProductDetail> findByProductQuery(int queryDay, Date startDate,
			Date endDate) {
		// 查询正常的产品
		List<ProductDetail> pdList = this.productDetailRepository
				.findByStatusOrderByIdAsc("1");

		if (pdList == null || pdList.size() == 0) {
			return new ArrayList<ProductDetail>();
		}

		// 查询区间断的历史收益表
		List<HisProductProfit> hppList = this.hisProductProfitRepository
				.findDateBetweenList(pdList, startDate, endDate);

		Date tmpDate = null;
		List<HisProductProfit> tmpHppList = null;
		HisProductProfit tmpHpp = null;
		boolean hasFlag = false;

		for (ProductDetail pd : pdList) {
			tmpHppList = new ArrayList<HisProductProfit>();
			for (int i = 0; i <= -queryDay; i++) {
				tmpDate = DateUtil.addDay(startDate, i);
				if (hppList != null) {
					for (HisProductProfit hpp : hppList) {
						// 查找对应的产品和日期，如果存在就加入，否则新建一个历史收益对象并加入
						if (hpp.getProductDetail() == pd
								&& DateUtil.dateFormat8(tmpDate).equals(
										DateUtil.dateFormat8(hpp
												.getCreateDate()))) {
							hpp.setCreatedate(DateUtil.dateFormat(tmpDate,
									"yyyy-MM-dd"));
							tmpHppList.add(hpp);
							hasFlag = true;
							break;
						}
					}
				}
				if (!hasFlag) {
					tmpHpp = new HisProductProfit();
					tmpHpp.setCreatedate(DateUtil.dateFormat(tmpDate,
							"yyyy-MM-dd"));
					tmpHpp.setQrnh(0);
					tmpHpp.setWfsy(0);
					tmpHppList.add(tmpHpp);
				}
				hasFlag = false;
			}
			pd.setHisProductProfitList(tmpHppList);
		}

		return pdList;
	}
}
